'use strict';

module.exports = () => {
  return async function auth(ctx, next) {
    // 跳过不需要认证的路由
    const publicRoutes = [
      '/api/auth/register',
      '/api/auth/login',
      '/api/properties',
      '/api/properties/',
      '/api/properties/*/reviews',
      '/api/properties/*/reviews/stats',
      '/'
    ];

    const isPublicRoute = publicRoutes.some(route => {
      if (route.includes('*')) {
        const pattern = route.replace('*', '.*');
        return new RegExp(pattern).test(ctx.path);
      }
      return ctx.path === route || ctx.path.startsWith(route + '/');
    });

    if (isPublicRoute) {
      await next();
      return;
    }

    // 获取token
    const token = ctx.headers.authorization?.replace('Bearer ', '') || ctx.query.token;

    if (!token) {
      ctx.status = 401;
      ctx.body = { success: false, message: '请先登录' };
      return;
    }

    try {
      // 这里应该验证JWT token，暂时简化处理
      // 在实际项目中，应该使用jwt库来验证token
      const user = await ctx.service.user.findById(parseInt(token));
      
      if (!user) {
        ctx.status = 401;
        ctx.body = { success: false, message: '用户不存在' };
        return;
      }

      // 将用户信息存储到ctx.state中
      ctx.state.user = {
        id: user.id,
        username: user.username,
        role: user.role
      };

      await next();
    } catch (error) {
      ctx.status = 401;
      ctx.body = { success: false, message: '认证失败' };
    }
  };
};
